import { login, logout, getInfo } from '@/api/system/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter, asyncRoutes, constantRoutes } from '@/router'
import cloneDeep from 'lodash/cloneDeep'
import router from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    permissions: [],
    resultAsyncRoutes: [],
    resultAllRputes: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO: (state, user) => {
    state.name = user.nickName
    state.avatar = user.avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_PERMISSION: (state, permissions) => {
    state.permissions = permissions
  },
  SET_RESULTASYNCROUTES: (state, asyncRoutes) => {
    state.resultAsyncRoutes = asyncRoutes
    state.resultAllRputes = constantRoutes.concat(asyncRoutes)
  }
}

const computedAsyncRoutes = (asyncRoutes, menuList) => {
  return asyncRoutes.filter(route => {
    if (menuList.includes(route.name)) {
      if (route.children && route.children.length) {
        route.children = computedAsyncRoutes(route.children, menuList)
      }
      return true
    }
    return false
  })
}

const actions = {
  async login({ commit }, userInfo) {
    try {
      const { username, password } = userInfo
      const result = await login({ userName: username.trim(), password: password })
      if (result.code === 200) {
        commit('SET_TOKEN', result.data.token)
        setToken(result.data.token)
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message || '登录失败'))
      }
    } catch (error) {
      return Promise.reject(error)
    }
  },

  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        if (!data) {
          reject(new Error('验证失败，请重新登录'))
          return
        }

        const { user, permissions, roles, menuList } = data
        
        // 设置用户信息
        commit('SET_USERINFO', user)
        commit('SET_ROLES', roles)
        commit('SET_PERMISSION', permissions)
        
        // 计算路由
        const accessRoutes = computedAsyncRoutes(cloneDeep(asyncRoutes), menuList)
        commit('SET_RESULTASYNCROUTES', accessRoutes)
        
        // 添加路由
        router.addRoutes(accessRoutes)
        
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken()
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken()
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

